#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unordered_map>
#include<ctype.h>
#include<sys/stat.h>
#include<fcntl.h>

#define COMMAND_SIZE 1024
#define FORMAT "[%s@%s %s]# "

//命令行参数表
#define MAXARGC 128
char* g_argv[MAXARGC];
int g_argc = 0;

//环境变量表
#define MAX_ENVS 128 
char* g_env[MAX_ENVS];
int g_envs = 0;

//别名映射表
std::unordered_map<std::string, std::string> alias_list;

//重定向，关心的内容
#define NONE_REDIR 0
#define INPUT_REDIR 1
#define OUTPUT_REDIR 2
#define APPEND_REDIR 3

int redir = NONE_REDIR;
std::string filename;

//for test 
char cwd[1024];
char cwdenv[1024];

//last exit code 
int lastcode = 0;

void InitEnv()
{
    extern char** environ;
    memset(g_env, 0, sizeof(g_env));
    g_envs = 0;
    
    //1.获取环境变量
    for(int i = 0; environ[i]; i++)
    {
        //申请空间
        g_env[i] = (char*)malloc(strlen(environ[i] + 1));
        //拷贝环境变量
        strcpy(g_env[i], environ[i]);
        g_envs++;
    }
    g_env[g_envs++] = (char*)"XZY=123456";
    g_env[g_envs] = NULL;

    //2.导入环境变量
    for(int i = 0; g_env[i]; i++)
    {
        putenv(g_env[i]);
    }
    
    environ = g_env;
}
    
//获取用户名
const char* GetUserName()
{
    const char* name = getenv("USER");
    return name == NULL ? "None" : name;
}

//获取主机名
const char* GetHostName()
{
    const char* name = getenv("HOSTNAME");
    return name == NULL ? "None" : name;
}

//获取当前路径
const char* GetPwd()
{
    //const char* pwd = getenv("PWD"); 根据环境变量PWD获得当前路径(当cd修改路径时：环境变量不会被修改)
    const char* ret = getcwd(cwd, sizeof(cwd)); //通过系统调用getcwd：获取当前路径cwd
    if(ret != NULL) //获取成功时：ret也是当前路径
    {
        snprintf(cwdenv, sizeof(cwdenv), "PWD=%s", cwd); //格式化环境变量"PWD=cwd"
        putenv(cwdenv); //更新环境变量"PWD=cwd"
    }
    return ret == NULL ? "None" : cwd;
}

//获取家目录
const char* GetHome()
{
    const char* home = getenv("HOME");
    return home == NULL ? "NULL" : home;
}

//根据当前绝对路径修改为相对路径
std::string DirName(const char* pwd)
{
#define SLASH "/"
    std::string dir = pwd;
    if(dir == SLASH) return SLASH;
    auto pos = dir.rfind(SLASH);
    if(pos == std::string::npos) return "BUG?";
    return dir.substr(pos + 1);
}

//制作命令行提示符
void MakeCommandLinePrompt(char prompt[], int size)
{
    //snprintf(prompt, size, FORMAT, GetUserName(), GetHostName(), DirName(GetPwd()).c_str()); 
    snprintf(prompt, size, FORMAT, GetUserName(), GetHostName(), GetPwd());
}

//打印命令行提示符
void PrintCommandLinePrompt()
{
    char prompt[COMMAND_SIZE];
    MakeCommandLinePrompt(prompt, sizeof(prompt));
    printf("%s", prompt);
    fflush(stdout);
}

//获取命令
bool GetCommand(char* command, int size)
{
    char* ret = fgets(command, size, stdin);
    if(ret == NULL) return false;
    command[strlen(command) - 1] = '\0'; //清理\n
    if(strlen(command) == 0) return false;
    return true;
}

//命令解析
bool CommandPrase(char* command)
{
#define SEP " "

    g_argc = 0;
    g_argv[g_argc++] = strtok(command, SEP);
    
    while((bool)(g_argv[g_argc++] = strtok(NULL, SEP)));
    g_argc--;

    return g_argc > 0 ? true : false;
}

//打印命令行参数
void PrintArgv()
{
    for(int i = 0; g_argv[i]; i++)
    {
        printf("argv[%d]：%s\n", i, g_argv[i]);
    }
    printf("argc：%d\n", g_argc);
}

//父进程执行cd命令
bool Cd()
{
    if(g_argc == 1)
    {
        std::string home = GetHome();
        if(home.empty()) return true;
        chdir(home.c_str());
    }
    else 
    {
        std::string where = g_argv[1];
        if(where == "~")
        {}
        else if(where == "-")
        {}
        else 
        {
            chdir(where.c_str());
        }
    }
    return true;
}

bool Echo()
{
    if(g_argc == 2)
    {
        std::string opt = g_argv[1];
        if(opt == "$?") //echo $?
        {
            std::cout << lastcode << std::endl;
            lastcode = 0;
        }
        else if(opt[0] == '$')
        {
            std::string env_name = opt.substr(1);
            const char* env_value = getenv(env_name.c_str());
            if(env_value)
                std::cout << env_value << std::endl;
        }
        else 
        {
            std::cout << opt << std::endl;
        }
    }
    return true;
}

//检测并执行内建命令：由父进程执行
bool CheckAndExecBuiltin()
{
    std::string cmd = g_argv[0];
    if(cmd == "cd")
    {
        Cd();
        return true;
    }
    else if(cmd == "echo")
    {
        Echo();
        return true;
    }
    else if(cmd == "export") 
    {
        //1.在环境变量表中查找环境变量名：是否存在
        //2.存在修改，不存在新增
    }
    else if(cmd == "alias")
    {
        //std::string nickname = g_argv[1];
        //alias_list.insert(k, v)
    }

    return false;
}

//执行普通命令：由子进程执行
void ExecuteCommand()
{ 
    pid_t id = fork();
    if(id == 0)
    {
        //子进程
        
        //子进程检查重定向情况，父进程不能重定向
        int fd = -1;
        if(redir == INPUT_REDIR)
        {
            fd = open(filename.c_str(), O_RDONLY);
            if(fd < 0) exit(1);
            dup2(fd, 0);
            close(fd);
        }
        else if(redir == OUTPUT_REDIR)
        {
            fd = open(filename.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0666);
            if(fd < 0) exit(2);
            dup2(fd, 1);
            close(fd);
        }
        else if(redir == APPEND_REDIR)
        {
            fd = open(filename.c_str(), O_CREAT | O_WRONLY | O_APPEND, 0666);
            if(fd < 0) exit(2);
            dup2(fd, 1);
            close(fd);
        }
        else 
        {}

        //进程替换不影响，重定向的结果
        execvp(g_argv[0], g_argv);
        exit(1);
    }
    //父进程
    int status = 0;
    pid_t rid = waitpid(id, &status, 0);
    if(rid > 0)
    {
        lastcode = WEXITSTATUS(status);
    }
}

void TrimSpace(char command[], int& end)
{
    while(isspace(command[end]))
    {
        end++;
    }
}

void RedirCheck(char command[])
{ 
    redir = NONE_REDIR;
    filename.clear();

    int start = 0, end = strlen(command) - 1;
    while(end > start)
    {
        if(command[end] == '<')
        {
            command[end++] = '\0';
            TrimSpace(command, end);
            redir = INPUT_REDIR;
            filename = command + end;
            break;
        }
        else if(command[end] == '>')
        {
            if(command[end - 1] == '>')
            {
                command[end - 1] = '\0';
                end++;
                TrimSpace(command, end);
                redir = APPEND_REDIR;
                filename = command + end;
                break;
            }
            else 
            {
                command[end++] = '\0';
                TrimSpace(command, end);
                redir = OUTPUT_REDIR;
                filename = command + end;
                break;
            }
        }
        else 
        {
            end--;
        }
    }
}

int main()
{
    //shell启动的时候，需用从系统中获取环境变量
    //我们的环境变量信息应该从父shell中获取
    InitEnv();

    while(true)
    {     
        //1.输出命令行提示符
        PrintCommandLinePrompt();

        //2.获取用户输入的命令
        char command[COMMAND_SIZE];
        if(!GetCommand(command, sizeof(command)))
            continue;

        //3.重定向分析："ls -a -l > file.txt" -> "ls -a -l" "file.txt" -> 判定重定向方式
        RedirCheck(command); 
        //printf("redir = %d, filename = %s\n", redir, filename.c_str());

        //4.命令解析："ls -a -l" -> "ls"、"-a"、"-l" 
        if(!CommandPrase(command))
            continue;
        //PrintArgv();
        
        //检测别名
        //5.检测并处理内建命令
        if(CheckAndExecBuiltin())
            continue;
        
        //6.执行命令
        ExecuteCommand();
    }

    return 0;
}
